/**
 * 
 */
package com.ideeli.webextractor.service;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.ideeli.webextractor.domain.ProductDetail;
import com.ideeli.webextractor.exception.ProductSkipException;
import com.ideeli.webextractor.utils.Utility;

/**
 * @author spaida
 *
 */
public class ExtractProductDetailServiceImpl implements
		ExtractProductDetailService {
	
	private static final Logger logger = Logger.getLogger(ExtractProductDetailServiceImpl.class);

	private CacheService cacheService;
	
	public ExtractProductDetailServiceImpl()
	{
		
	
	}
	
	
	/* (non-Javadoc)
	 * @see com.ideeli.webextractor.service.ExtractProductDetailService#extract(org.openqa.selenium.WebDriver)
	 */
	@Override
	public ProductDetail extract(WebDriver driver) throws Exception 
	{
		logger.warn("extract()");
			ProductDetail prodDetail= new ProductDetail();
			
			try{
				
				WebElement productNameWE = driver.findElement(By.className("product-name"));
				logger.warn("productNameWE  : " + productNameWE.getText());
				prodDetail.setProductName(productNameWE.getText());
				
				WebElement vendorWE = driver.findElement(By.className("vendor"));
				String vendor=vendorWE.getText();
				vendor = vendor.replace("by", "");
				vendor = vendor.trim();
				logger.warn("vendorWE  : " + vendor);
				prodDetail.setVendor(vendor);

				WebElement categoryTableWE = driver.findElement(By.className("category-table"));
				logger.info("categoryTableWE  : " + categoryTableWE.getText());
				Utility.parseCategory(categoryTableWE.getText(), prodDetail);
				
				WebElement yourPriceWE = driver.findElement(By.className("your-price"));
				logger.info("yourPriceWE  : " + yourPriceWE.getText());
				prodDetail.setYourPrice(Utility.extractPrice(yourPriceWE.getText()));

				WebElement inStockWE = driver.findElement(By.className("in-stock"));
				logger.info("inStockWE  : " + inStockWE.getText());
				prodDetail.setInStock("In Stock".equals(inStockWE.getText().trim())? true : false);

				WebElement infoCodesWE = driver.findElement(By.className("info-codes"));
				logger.info("infoCodesWE  : " + infoCodesWE.getText());
				Utility.parseInfoCodesWE(infoCodesWE.getText(), prodDetail);
				

				WebElement productInformationWE = driver.findElement(By.id("product-information"));
				logger.debug("productInformationWE  : " + productInformationWE.getText());
				prodDetail.setProductInformation(productInformationWE.getText());
				Utility.parseBasicProdInformation(productInformationWE.getText(), prodDetail);
				
				String innerHtml=productInformationWE.getAttribute("innerHTML");
				prodDetail.setBasicSpecHtml(innerHtml);
				logger.debug("innerhtml");
				logger.debug(innerHtml);
			
				try
				{
					WebElement extendedSpecSelWE = driver.findElement(By.id("selector-extended-specifications"));
					extendedSpecSelWE.click();
					logger.debug("extendedSpecSelWE  : " + extendedSpecSelWE.getText());//NoText just for clicking purpose
				}
				catch(Throwable nse)
				{
					System.out.println("selector-extended-specifications does not exist ! skip");
					
				}

				try
				{
					WebElement extendedSpecWE = driver.findElement(By.id("extended-specifications"));
					logger.debug("extendedSpecWE  : " + extendedSpecWE.getText());
					prodDetail.setExtendedSpec(extendedSpecWE.getText());
					Utility.parseExtendedProdInformation(extendedSpecWE.getText(), prodDetail);
					innerHtml=extendedSpecWE.getAttribute("innerHTML");
					logger.debug("innerhtml:"+innerHtml);
					prodDetail.setExtendedSpecHtml(Utility.formatExtendedHtml(innerHtml));
					
				}
				catch(Throwable nse)
				{
					System.out.println("extended-specifications  does not exist ! skip");
				}

				

				WebElement prodImageWE = driver.findElement(By.id("ctl00_PlaceHolderMain_pdTopControl_uc_ProductDetailsImageControl_lnk_ImageLink"));
				logger.debug("prodImageWE  : " + prodImageWE.getText());
				
				String srcLink=prodImageWE.getAttribute("href");
				logger.info("srcLink  : " + srcLink);
				String largeImgFleName=prodDetail.getSku()+".jpg";

				//Device fileName from here.
				if(srcLink!=null && !srcLink.contains("no-photo-lg"))
				{
					try
					{
						Utility.saveImage(srcLink, cacheService.getActualImagePath()+largeImgFleName);	
					}
					catch(Exception e)
					{
						try
						{
							logger.info("can't download large image, try small one");
							String sImgFleName=prodDetail.getSku()+"-95.jpg";
							srcLink=srcLink.replaceAll("/300/", "/95/");
							Utility.saveImage(srcLink, cacheService.getActualImagePath()+sImgFleName);
							largeImgFleName=sImgFleName;
						}
						catch(Exception ex)
						{
							logger.error("store without image");
						}
					}

					
//					change small image to large only
//					srcLink=srcLink.replaceAll("300", "95");
//					logger.info("srcLink  : " + srcLink);
//					Utility.saveImage(srcLink, smallBasePath+sImgFleName);
//					prodDetail.setSmallImage("data/images/small/"+sImgFleName);
					
					prodDetail.setSmallImage("data/images/large/"+largeImgFleName);
					prodDetail.setLargeImage("data/images/large/"+largeImgFleName);
				}
				else
				{
					prodDetail.setLargeImage("data/images/brands/"+vendor+cacheService.getExtension(vendor));
					prodDetail.setSmallImage("data/images/brands/"+vendor+cacheService.getExtension(vendor));
				}
				
			}
			
			catch(Exception e)
			{
				logger.info("skipping this product...:");
				logger.error(e);
				e.printStackTrace();
				throw new ProductSkipException("element not found:",e);	
			}
			
			return prodDetail;
		}


	public CacheService getCacheService() {
		return cacheService;
	}


	public void setCacheService(CacheService cacheService) {
		this.cacheService = cacheService;
	}


	



}
